600. Testing with Jest
- Testing | NestJS - A progressive Node.js framework
- In nest, you can use any testing framework that you like, as Nest doesn't force any specific tooling.
Unit Testing with Jest
Installation
npm i --save-dev @nestjs/testing
Run Test Commands
npm run test # for unit tests
npm run test:cov # for test coverage
npm run test:e2e # for e2e tests
npm run test:watch -- coffees.service # run specific sile in watch mode
- test files end with [name].spec.ts
- coffee.controller.spec.ts
- coffee.service.spec.ts
- write tests as self-explanatory code, check the following example
describe('findOne', () => {
describe('when user exists', () => {
it('should return user', () => {
expect(appController.findOne(1)).toEqual({
id: 1,
name: 'user1',
});
});
});
describe('when user does not exist', () => {
it('should return null', () => {
expect(appController.findOne(2)).toBeNull();
});
})
})
- close app after running e2e tests
- nest will give you warning about
Jest did not exit one second after the test run has completed
- to fix this
- add an
afterAll
jest method to close the app - change
beforeEach
tobeforeAll
, we don't want to recreate the whole app ine2e
tests for each test
- add an
- nest will give you warning about
beforeAll(async () => {
await app.init();
})
//tests...
afterAll(async () => {
await app.close();
})
- npm has a pre-built in option, to make commands run before and after a certain command is executed
- for example: we can create a test db before running a test and remote the test db after running the test, just using npm
- to do this, add
pre[npmcommand]
, or/andpost[npmcommand]
"pretest:e2e": "docker compose up -d test-db",
"test:e2e": "jest ...",
"posttest:e2e": "docker compose stop test-dp && docker compose rm -f test-db"
HTTP Testing with Supertest
- Testing | NestJS - A progressive Node.js framework
- Keep your e2e test files inside the test directory. The testing files should have a
.e2e-spec
suffix.coffee.service.e2e-spec.ts
it(`/GET cats`, () => {
return request(app.getHttpServer())
.get('/cats')
.expect(200)
.expect({
data: catsService.findAll(),
});
});